package com.jeeplus.modules.monitor.task;

import org.apache.shiro.util.ThreadContext;
import org.quartz.DisallowConcurrentExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jeeplus.common.utils.SpringContextHolder;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.modules.grouporder.entity.GroupOrder;
import com.jeeplus.modules.grouporder.service.GroupOrderService;
import com.jeeplus.modules.monitor.entity.Task;
import com.jeeplus.modules.productorder.entity.ProductOrder;
import com.jeeplus.modules.productorder.service.ProductOrderService;

/**
 * 自动收货
 * @author Administrator
 *
 */
@DisallowConcurrentExecution  
public class FinishOrderTask extends Task {
	private static ProductOrderService productOrderService = SpringContextHolder.getBean(ProductOrderService.class);
	private static GroupOrderService groupOrderService = SpringContextHolder.getBean(GroupOrderService.class);

	private static final org.apache.shiro.mgt.SecurityManager MANAGER = SpringContextHolder.getBean(org.apache.shiro.mgt.SecurityManager.class);
	private static Logger logger = LoggerFactory.getLogger(FinishOrderTask.class);
	
	@Override
	public void run() {
		if (ThreadContext.getSecurityManager() == null) {
			ThreadContext.bind(MANAGER);
		}
		// 云店订单
		ProductOrder productOrder = new ProductOrder();
		productOrder.setState("2");
		productOrder.setDataScope(" AND a.expire_date < NOW() ");
		int pageNum = 1;
		while (true) {
			Page<ProductOrder> page = productOrderService.findPage(new Page<ProductOrder>(pageNum, 100), productOrder);
			if (!page.getList().isEmpty()) {
				for (ProductOrder order : page.getList()) {
					order.setState("3");
					order.setFinishDate(order.getExpireDate());
					try {
						productOrderService.finish(order);
					} catch (Exception e) {
						logger.error("云店订单" + order.getId() + "确认收货失败：" + e.getMessage());
					}
				}
			}
			if (page.getList().size() < 100) {
				break;
			}
			pageNum++;
		}
		
		// 拼团订单
		GroupOrder groupOrder = new GroupOrder();
		groupOrder.setState("2");
		groupOrder.setDataScope(" AND a.expire_date < NOW() ");
		int pageNo = 1;
		while (true) {
			Page<GroupOrder> page = groupOrderService.findPage(new Page<GroupOrder>(pageNo, 100), groupOrder);
			if (!page.getList().isEmpty()) {
				for (GroupOrder order : page.getList()) {
					order.setState("3");
					order.setFinishDate(order.getExpireDate());
					try {
						groupOrderService.finish(order);
					} catch (Exception e) {
						logger.error("拼团订单" + order.getId() + "确认收货失败：" + e.getMessage());
					}
				}
			}
			if (page.getList().size() < 100) {
				break;
			}
			pageNo++;
		}
	}
}
